import 'dart:convert';
import 'dart:io';
import 'package:draggable_fab/draggable_fab.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:ichinesereader/controller/audiobooks.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/recorder.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/models/student/assignmentSettings.dart';
import 'package:ichinesereader/pages/common/myRecorder.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'dart:collection';
import '../../models/common/Settings.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/controller/cache.dart';
import '../common/bookBar.dart';

var notext = 'No Text';

enum TextOptions { Simplified, Traditional, notext }

enum AudioOptions { Mandarin, Cantonese, No_audio }

enum AutoplayOptions { True, False }

enum PinyinOptions { True, False }

TextOptions? text;
AudioOptions? audio;
AutoplayOptions? auto;
PinyinOptions? pinyinS;

//使用webview的方式打开书；此插件只支持apps，桌面版和web版暂不支持
class InAppWebViewAppBookScreen extends StatefulWidget {
  InAppWebViewAppBookScreen({
    Key? key,
    this.bookId,
    required this.bookCode,
    this.bookTitle,
    this.assignmentId,
    required this.readingType,
    this.userName,
  }) : super(key: key);
  final String? bookId;
  final String bookCode;
  final String? bookTitle;
  final String? assignmentId;
  final String? userName;
  final NanhaiBookReadingTypes readingType;

  static const String routeName = '/student/book';

  @override
  _InAppWebViewAppBookScreenState createState() =>
      new _InAppWebViewAppBookScreenState();
}

var globalController;
var iFrame;
final box = Hive.box('appconfig');

class _InAppWebViewAppBookScreenState extends State<InAppWebViewAppBookScreen> {
  final GlobalKey webViewKey = GlobalKey();
  final BooksController _booksController = Get.find();
  final UserController _usersController = Get.find();
  final AudioBooksController _audioBooksController =
      Get.put(AudioBooksController());
  RecorderController _recorderController = Get.put(RecorderController());
  InAppWebViewController? webViewController;
  InAppWebViewSettings options = InAppWebViewSettings(
      useShouldOverrideUrlLoading: true,
      mediaPlaybackRequiresUserGesture: false,
      useHybridComposition: true,
      allowsInlineMediaPlayback: true,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      cacheEnabled: true,
      domStorageEnabled: true,
      javaScriptEnabled: true,
      allowsPictureInPictureMediaPlayback: true,
      enableViewportScale: true,
      disableLongPressContextMenuOnLinks: true,
      //requestedWithHeaderMode: RequestedWithHeaderMode.NO_HEADER,
      //iframeAllow: "camera; microphone",
      //iframeAllowFullscreen: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  late PullToRefreshController pullToRefreshController;
  late ContextMenu contextMenu;
  AssignmentSettings _assignmentSettingsDto = new AssignmentSettings();
  var textDisplay, textToggle = true, voices, dictionary, music, noAudio;
  String url = '';
  String _authtoken = '';
  // // seems not used in app webview
  //int _numBooks = 0;
  //int _points = 0;
  //String _gender = '';
  String _lang = '';
  String _language = '';
  bool _pinyin = true;
  String _bookBasePath = '';
  String _bookCode = '';
  String _bookId = '';
  bool _vocabulary = true;
  bool updateProgress = false;
  bool isFinished = false;
  bool hasSentData = false;
  double ratio = 1;

  double progress = 0;
  final urlController = TextEditingController();

  CookieManager cookieManager = CookieManager.instance();
  final box = Hive.box('appconfig');
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;
  @override
  void initState() {
    super.initState();
    //_recorderController.setToDefault();
    box.put(CacheManagerKey['_isFinished'].toString(), false);
    // // seems not used in app webview
    // _numBooks = box.get('UserNumBooks') ?? 0;
    // _points = box.get('UserPoints') ?? 0;
    // _gender = box.get('UserGender') ?? '';
    _authtoken = box.get(CacheManagerKey['authtoken'].toString()) ?? '';
    if (widget.assignmentId != null && widget.assignmentId != '') {
      _lang = box.get('UserAssiLang') ?? 'Mandarin';
      _language = box.get('UserAssiLanguage') ?? 'Simplified';
    } else {
      _lang = box.get('UserLang') ?? 'Mandarin';
      _language = box.get('UserLanguage') ?? 'Simplified';
      _pinyin = box.get('UserPinyin') ?? true;
    }
    var settings = json.decode(
        box.get(CacheManagerKey['profilesettings'].toString()).toString());
    _vocabulary = settings != null && settings['vocabulary'] != null
        ? settings['vocabulary']
        : true;
    // seems this cookies are useless
    // loadautoken();
    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Student ||
        box.get(CacheManagerKey['nanhairole'].toString()) ==
            Constants.NanhaiRole_Individual) {
      updateProgress = true;
    }

    _bookCode = widget.bookCode;
    _bookId = widget.bookId ?? '';
    _bookBasePath =
        'https://resources.ichinesereader.com/books/$_bookCode/assets';

    if (_bookId != '') {
      _booksController.setCurrentBookId(_bookId);
    }

    if (widget.assignmentId != null && widget.assignmentId != '') {
      var assignmentSettings = _booksController.getCurrentAssignmentSettings();
      _assignmentSettingsDto.id = widget.assignmentId;
      if (assignmentSettings != null) {
        _assignmentSettingsDto.lang = assignmentSettings.lang;
        _assignmentSettingsDto.language = assignmentSettings.language;
        _assignmentSettingsDto.audio = assignmentSettings.audio;
        _assignmentSettingsDto.dictionary = assignmentSettings.dictionary;
        _assignmentSettingsDto.music = assignmentSettings.music;
        _assignmentSettingsDto.pinyin = assignmentSettings.pinyin;
        _assignmentSettingsDto.quizAudio = assignmentSettings.quizAudio;
      }
    }

    pullToRefreshController = PullToRefreshController(
      onRefresh: () async {
        if (Platform.isAndroid) {
          webViewController?.reload();
        } else if (Platform.isIOS) {
          webViewController?.loadUrl(
              urlRequest: URLRequest(url: await webViewController?.getUrl()));
        }
      },
    );
  }

  @override
  void dispose() {
    _audioBooksController.stop();
    globalController = null;
    super.dispose();
    // SystemChrome.setPreferredOrientations([
    //   DeviceOrientation.landscapeRight,
    //   DeviceOrientation.landscapeLeft,
    //   DeviceOrientation.portraitUp,
    //   DeviceOrientation.portraitDown,
    // ]);
  }

  // void loadautoken() async {
  //   await cookieManager.setCookie(
  //     url: WebUri(Constants.BaseURL),
  //     name: "nanhaiV4.8Role",
  //     value: box.get(CacheManagerKey['nanhairole'].toString()) ?? '',
  //     domain: Constants.BaseDomain,
  //     path: '/',
  //     expiresDate: expiresDate,
  //     isSecure: true,
  //   );

  //   if (box.get(CacheManagerKey['nanhairole'].toString()) ==
  //       Constants.NanhaiRole_Student) {
  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8StudentSession",
  //       value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );

  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8StudentUserId",
  //       value: box.get(CacheManagerKey['username'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );
  //   }

  //   if (box.get(CacheManagerKey['nanhairole'].toString()) ==
  //       Constants.NanhaiRole_Individual) {
  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8IndividualSession",
  //       value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );

  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8IndividualUserId",
  //       value: box.get(CacheManagerKey['username'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );
  //   }

  //   if (box.get(CacheManagerKey['nanhairole'].toString()) ==
  //       Constants.NanhaiRole_SchoolAdmin) {
  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8SchooladminSession",
  //       value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );

  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8SchooladminUserId",
  //       value: box.get(CacheManagerKey['username'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );
  //   }

  //   if (box.get(CacheManagerKey['nanhairole'].toString()) ==
  //       Constants.NanhaiRole_Teacher) {
  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8TeacherSession",
  //       value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );

  //     await cookieManager.setCookie(
  //       url: WebUri(Constants.BaseURL),
  //       name: "nanhaiV4.8TeacherUserId",
  //       value: box.get(CacheManagerKey['username'].toString()) ?? '',
  //       domain: Constants.BaseDomain,
  //       path: '/',
  //       expiresDate: expiresDate,
  //       isSecure: true,
  //     );
  //   }

  //   if (box.get(CacheManagerKey['nanhairole'].toString()) ==
  //           Constants.NanhaiRole_Student ||
  //       box.get(CacheManagerKey['nanhairole'].toString()) ==
  //           Constants.NanhaiRole_Individual) {
  //     updateProgress = true;
  //   }
  // }

  void finishBook() {
    isFinished = true;
    box.put(CacheManagerKey['_isFinished'].toString(), isFinished);
  }

  String settingsToJson(Settings? data) => json.encode(data!.toJson());

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;
    // double width = 2000;
    // double height = 1500;
    var hr, wr;
    var viewMode = box.get(CacheManagerKey['_viewMode'].toString());
    if (viewMode == 'LANDSCAPE') {
      hr = (height - AppBar().preferredSize.height) / 728;
      wr = width / 1024;
      if (hr < wr) {
        ratio = hr;
      } else {
        ratio = wr;
      }
    } else {
      // avoid to cut bottom text
      //hr = (height - AppBar().preferredSize.height - 40) / 984;
      hr = (height - AppBar().preferredSize.height) / 984;
      wr = width / 768;
      if (hr < wr) {
        ratio = hr;
      } else {
        ratio = wr;
      }
    }
    //print(ratio);
    if (ratio > 1.10) {
      ratio = 1.10;
    }

    // for initial book
    if (widget.assignmentId != null && widget.assignmentId != '') {
      if (_assignmentSettingsDto.language == 'Simplified') {
        textDisplay = 's';
      } else if (_assignmentSettingsDto.language == 'Traditional') {
        textDisplay = 't';
      } else {
        textToggle = false;
      }
      if (_lang == 'Mandarin' || _lang == 'Cantonese') {
        voices = true;
      } else {
        voices = false;
      }
      noAudio = _lang == "No_audio";
      music = voices;
      // voices = _assignmentSettingsDto.audio;
      // music = _assignmentSettingsDto.music;
      dictionary = _assignmentSettingsDto.dictionary;
      _pinyin = _assignmentSettingsDto.pinyin ?? true;
    } else {
      if (_language == 'Simplified') {
        textDisplay = 's';
      } else if (_language == 'Traditional') {
        textDisplay = 't';
      } else {
        textToggle = false;
      }
      if (_lang == 'Mandarin' || _lang == 'Cantonese') {
        voices = true;
      } else {
        voices = false;
      }
      noAudio = _lang == "No_audio";
      music = voices;
      _pinyin = box.get('UserPinyin') ?? true;
      dictionary = true;
      var boxPinyin = 'True';
      if (_pinyin) {
        boxPinyin = 'True';
      } else {
        boxPinyin = 'False';
      }
      box.put(CacheManagerKey['_text'].toString(), _language.toString());
      box.put(CacheManagerKey['_audio'].toString(), _lang.toString());
      box.put(CacheManagerKey['_auto'].toString(), 'False'.toString());
      box.put(CacheManagerKey['_pinyin'].toString(), boxPinyin);
    }
    var myUserScripts;
    var srcEvaluation = """// url for test
                // var preURLSuper = "https://superbe.migration.ichinesereader.com";
                var preURLSuper = '${Constants.BaseAPISuper}';

                // for upload recording
                var preURL = '${Constants.BaseAPI}';
                 
                const admin = 'superadmin';

                function getAuthToken(value) {
                    var token = localStorage.getItem('authToken');
                    return token || value;
                }
                function getBookId() {
                    var bookId = localStorage.getItem('bookID');
                    return bookId || (window.bookInstance && window.bookInstance.id);
                }
                function getBookCode(value) {
                    var bookCode = localStorage.getItem('bookCode');
                    return bookCode || value;
                }
                function getLanguage(value) {
                    var language = localStorage.getItem('siteLang');
                    return language || value;
                }
                function getBilingualLanguage(value) {
                    var bilingualLanguage = localStorage.getItem('lang');
                    return bilingualLanguage || value;
                }
                function getWordMode(value) {
                    var lang = localStorage.getItem('language');
                    return lang || value;
                }
                function getUserName(value) {
                    var userName = localStorage.getItem('userName');
                    return userName || value;
                }
                // function to get word lists for each book
                // bookCode:string from localStorage bookCode, AuthToken:string from localStorage AuthToken, language:string from localStorage siteLang, wordMode:string from localStorage language, bilingualLanguage :string from localStorage lang
                // to test in book editer, you can test with some static data
                // language: Simplified,(Korean will be considered later..)
                function getBookWordList(bookCode, authToken, language, wordMode, bilingualLanguage){
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "GET",
                        url:  preURLSuper + admin + '/knowledge/word/book/' + getBookCode(bookCode),
                        data: { 
                            language: 'English', 
                            // simplified: getWordMode(wordMode) === 'Simplified', 
                            // mandarin: getBilingualLanguage(bilingualLanguage) === 'Mandarin',
                            simplified: getWordMode(wordMode), 
                            mandarin: getBilingualLanguage(bilingualLanguage),
                        },
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            //console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }
                // for AI audio test
                // parse the audio file
                // authToken: from localStorage AuthToken
                function AudioTest(file, authToken){
                    var fd = new FormData();
                    fd.append('file', file);

                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURLSuper + admin + '/speech/recognition',
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        data: fd,
                        processData: false,
                        contentType: false,
                        success: function(response){
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }

                // this function is called when want to save the recording
                // questions: Json object. the anwser in each qustion should be the following format 
                //           (['answer1'], or ['answer1', 'answer2'...], or ['match1|answer1', 'match2|answer2'...])
                // bilingualLanguage: Mandarin or Cantonese from localStorage lang
                // wordMode: Simplified or Traditional from localStorage language
                // userName: string from localStorage userName
                // authToken: from localStorage AuthToken
                // bookCode: from localStorage bookCode

                function createQuestionRecord(questions, bilingualLanguage, wordMode, userName, bookCode, authToken){
                    var defer = jQuery.Deferred();

                    let questionRecordForm = {
                        "assessmentId": null,
                        "audioType": getBilingualLanguage(bilingualLanguage),
                        "bookCode": getBookCode(bookCode),
                        "kind": "CUSTOMIZE",
                        "mode": "Exercise",
                        "questionGroupId": null,
                        "record": questions,
                        "textType": getWordMode(wordMode),
                        "type": "CUSTOMIZE",
                        "userName": getUserName(userName)
                    }
                    jQuery.ajax({
                        type: "POST",
                        url:  preURLSuper + admin + "/question/record",
                        data: JSON.stringify(questionRecordForm),
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            //console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }
                // this function is use to submit the evaluation and will be called when complete the pyp series book's anwsers
                // questions: Json object. the anwser in each qustion should be the following format (['answer1'], or ['answer1', 'answer2'])
                // bilingualLanguage: Mandarin or Cantonese from localStorage lang
                // wordMode: Simplified or Traditional from localStorage language
                // userName: string from localStorage userName
                // authToken: from localStorage AuthToken
                // bookCode: from localStorage bookCode

                function assessmentEvaltest(questions, bilingualLanguage, wordMode, userName, bookCode, authToken){
                    var defer = jQuery.Deferred();
                    // otherwise there is error when calling assessmentEvaltest finction when no audio
                    var _lang = '$_lang';
                    if (_lang == "No_audio") {
                      _lang = "Mandarin";
                    }
                    var questionRecordForm = {
                       "assessmentId": null,
                        "audioType": _lang,
                        "bookCode": '$_bookCode',
                        "kind": "CUSTOMIZE",
                        "mode": "Exercise",
                        "questionGroupId": null,
                        "record": questions,
                        "textType": '$_language',
                        "type": "CUSTOMIZE",
                        "userName": '${widget.userName}'
                    }
                    jQuery.ajax({
                        type: "POST",
                        url:  preURLSuper + admin + "/question/assessment/test",
                        data: JSON.stringify(questionRecordForm),
                        beforeSend: function (request) {
                            if (authToken) {
                              request.setRequestHeader("AuthToken", '$_authtoken');
                            }
                        },
                        contentType: 'application/json',
                        success: function(response){
                            console.log(response);
                            defer.resolve(response);
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                          //alert(xhr.status);
                        }
                        
                    });
                }

                // called when save the words to server
                // authToken: from localStorage AuthToken
                function saveWord(wordId, authToken){  
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURLSuper + admin + '/knowledge/word/save/' + wordId,
                        async: false,
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        success: function(response){
                            // console.log(response);
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }

                // Save recording file and return recording address fileId 
                // authToken: from localStorage AuthToken
                function uplodeRecordFileInBook(fd, authToken){
                    var defer = jQuery.Deferred();
                    jQuery.ajax({
                        type: "POST",
                        url: preURL + '/studentmanager/file',
                        beforeSend: function (request) {
                            if (authToken) {
                                request.setRequestHeader("AuthToken", getAuthToken(authToken));
                            }
                        },
                        data: fd,
                        processData: false,
                        contentType: false,
                        success: function(response){
                            defer.resolve(response);
                        }
                    });
                    return defer.promise();
                }
                """;

    if (widget.assignmentId != null && widget.assignmentId != '') {
      //_assignmentSettings = _booksController.getCurrentAssignmentSettings();
      myUserScripts = [
        UserScript(
            source:
                "window.localStorage.setItem('userName','${widget.userName}');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source:
                "window.sessionStorage.setItem('assignmentId','${widget.assignmentId}')",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('bookCode','$_bookCode');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('bookID','${widget.bookId}');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('authToken','$_authtoken');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('lang','$_lang');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('language','$_language');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source:
                "window.localStorage.setItem('bookBasePath','$_bookBasePath');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: srcEvaluation,
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        // for content
        UserScript(source: """
                document.getElementsByTagName('html')[0].style.maxWidth='initial';
                document.getElementsByTagName('html')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.transform='scale($ratio)'
                document.getElementsByTagName('body')[0].style.transformOrigin='top center';
                if($_vocabulary == false){
                  var element = document.getElementById("book-sgmt");
                  element.parentNode.removeChild(element);
                }
                // var font = innerDoc.getElementById('mti_wfs_colophon');
                // if(font){
                //   font.parentNode.removeChild(font);
                // }
                """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
        UserScript(
            source:
                """document.getElementById('play-start').style.backgroundImage="url('https://resources.ichinesereader.com/common/images/play_button.2d9092f6.png')";""",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
        UserScript(source: """window.updatePage = function (page, total) {
                  if(page == total){
                    console.log(true)}
                  }
                  """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
      ];
    } else {
      myUserScripts = [
        UserScript(
            source: "window.sessionStorage.removeItem('assignmentId')",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source:
                "window.localStorage.setItem('userName','${widget.userName}');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('bookCode','$_bookCode');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('authToken','$_authtoken');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('lang','$_lang');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('language','$_language');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source:
                "window.localStorage.setItem('bookBasePath','$_bookBasePath');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: "window.localStorage.setItem('bookID','${widget.bookId}');",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        UserScript(
            source: srcEvaluation,
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
        // for content
        UserScript(source: """
                document.getElementsByTagName('html')[0].style.maxWidth='initial';
                document.getElementsByTagName('html')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.width='auto';
                document.getElementsByTagName('body')[0].style.transform='scale($ratio)'
                document.getElementsByTagName('body')[0].style.transformOrigin='top center';
                // var font = document.getElementById('mti_wfs_colophon');
                if($_vocabulary == false){
                  var element = document.getElementById("book-sgmt");
                  element.parentNode.removeChild(element);
                }
                // var font = innerDoc.getElementById('mti_wfs_colophon');
                // if(font){
                //   font.parentNode.removeChild(font);
                // }

                // font.parentNode.removeChild(font);
                // var scripts = document.getElementsByTagName('script');
                // // check if there is audio in last page, then computer the delay value
                // console.log('script--total-',  scripts.length);
                // for(var i = 0; i < scripts.length; i++){
                //   console.log('script---', scripts[i].innerHTML);
                //   words = scripts[i].innerHTML;
                // }
                """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
        UserScript(
            source:
                """document.getElementById('play-start').style.backgroundImage="url('https://resources.ichinesereader.com/common/images/play_button.2d9092f6.png')";""",
            injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
        UserScript(source: """window.updatePage = function (page, total) {
                  if(page == total){
                    console.log(true)}
                  }
                  """, injectionTime: UserScriptInjectionTime.AT_DOCUMENT_END),
      ];
    }
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: PreferredSize(
          preferredSize: Size.fromHeight(38.0),
          child: AppBar(
              leading: BackButton(
                onPressed: () {
                  //_booksController.updateBookItemStatus(widget.readingType);
                  // if (updateProgress == true) {
                  //   //_usercontroller.getProfile();
                  //   //_booksController.refreshLevelPercentage();
                  //   _usersController.refreshLevelPercentage();
                  //   _recorderController.closeRecordState();
                  //   _booksController.setShowBookBarClose();
                  // }
                  // Navigator.of(context).pop();
                  // if (isFinished &&
                  //     updateProgress &&
                  //     !box.get(CacheManagerKey['_callEva']) &&
                  //     (widget.assignmentId == null ||
                  //         widget.assignmentId == ''))
                  //   // for test
                  //   //if (true)
                  //   showDialog(
                  //       context: context,
                  //       builder: (BuildContext context) {
                  //         return RecBookDialog(
                  //           bcode: widget.bookCode!,
                  //           btitle: widget.bookTitle!,
                  //           bid: widget.bookId!,
                  //           assignmentId: widget.assignmentId,
                  //           readingType: widget.readingType,
                  //           userName: '',
                  //           quizAvailable: box.get(
                  //               CacheManagerKey['_quizAvailable'].toString()),
                  //           readComplete: true,
                  //         );
                  //       });
                  _recorderController.closeRecordState();
                  _booksController.setShowBookBarClose();
                  if (isFinished && updateProgress) {
                    //_usersController.refreshLevelPercentage();
                    _booksController.updateBookStatus(
                        widget.bookId.toString(), widget.readingType);
                  }
                  if (isFinished &&
                      updateProgress &&
                      !box.get(CacheManagerKey['_callEva']) &&
                      (widget.assignmentId == null ||
                          widget.assignmentId == '')) {
                    Future.delayed(Duration(milliseconds: 100), () {
                      Navigator.of(context).pop();
                      // not call recommand book temply
                      // _booksController
                      //     .getRecommendedBookItems(widget.bookId.toString())
                      //     .then((items) {
                      //   if (items.isNotEmpty) {
                      //     showGeneralDialog(
                      //         context: Get.context as BuildContext,
                      //         transitionDuration: Duration(milliseconds: 400),
                      //         pageBuilder: (bc, ania, anis) {
                      //           return RecommendBookDialog(books: items);
                      //         });
                      //   }
                      // });
                    });
                  } else {
                    Future.delayed(Duration(milliseconds: 800), () {
                      Navigator.of(context).pop();
                    });
                  }
                },
              ),
              title: Row(
                children: [
                  Text(widget.bookTitle.toString().tr),
                  Expanded(child: Text('')),
                  if (widget.bookId != null)
                    BookBar(
                        bookId: widget.bookId!,
                        assignmentId: widget.assignmentId ?? '',
                        readingType: widget.readingType,
                        bookCode: widget.bookCode,
                        bookTitle: widget.bookTitle,
                        userName: widget.userName)
                ],
              ))),
      body: SafeArea(
          child: Column(children: <Widget>[
        Expanded(
          child: Stack(
            children: [
              InAppWebView(
                key: webViewKey,
                initialUrlRequest: URLRequest(
                    url: WebUri(
                        'https://resources.ichinesereader.com/books/$_bookCode/content.html')),
                initialUserScripts:
                    UnmodifiableListView<UserScript>(myUserScripts),
                initialSettings: options,
                pullToRefreshController: pullToRefreshController,
                onLoadStart: (controller, url) async {},
                onWebViewCreated: (controller) async {
                  webViewController = controller;
                },
                onPermissionRequest: (controller, request) async {
                  return PermissionResponse(
                      resources: request.resources,
                      action: PermissionResponseAction.GRANT);
                },
                shouldOverrideUrlLoading: (controller, navigationAction) async {
                  var uri = navigationAction.request.url!;

                  if (![
                    "http",
                    "https",
                    "file",
                    "chrome",
                    "data",
                    "javascript",
                    "about"
                  ].contains(uri.scheme)) {
                    if (await canLaunchUrl(uri)) {
                      // Launch the App
                      await launchUrl(
                        uri,
                      );
                      // and cancel the request
                      return NavigationActionPolicy.CANCEL;
                    }
                  }
                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
                  Log.debug('****____ONSTOP_______*********');
                  pullToRefreshController.endRefreshing();
                  globalController = controller;
                  Future.delayed(const Duration(milliseconds: 500), () async {
                    await controller.evaluateJavascript(source: """
                            if($noAudio){
                              readOff();
                              bgmOff();
                            }else{
                              readOn();
                              bgmOn();
                              fLangToggle('${_lang[0].toLowerCase()}');
                            }
                            init(
                              '${widget.bookTitle}',
                              '${widget.bookTitle}',
                              $music,
                              $voices,
                              false,
                              '$textToggle',
                              '$textDisplay',
                              $_pinyin,
                              $dictionary,
                              '${box.get(CacheManagerKey['nanhairole'].toString())}'
                            );
                            """);
                  });
                },
                onReceivedError: (controller, request, error) {
                  pullToRefreshController.endRefreshing();
                },
                onProgressChanged: (controller, progress) {
                  if (progress == 100) {
                    pullToRefreshController.endRefreshing();
                  }
                  // this will caused mutiple buid
                  setState(() {
                    this.progress = progress / 100;
                    //urlController.text = this.url;
                  });
                },
                onUpdateVisitedHistory: (controller, url, androidIsReload) {
                  setState(() {
                    this.url = url.toString();
                    urlController.text = this.url;
                  });
                },
                onConsoleMessage: (controller, consoleMessage) async {
                  if (consoleMessage.message == 'true' && updateProgress) {
                    Future.delayed(Duration(milliseconds: 1200), (() {
                      _booksController
                          .readProgress(widget.bookId, widget.assignmentId, 100,
                              widget.readingType)
                          .then((statusMessage) {
                        if (statusMessage.status == 1000) {
                          finishBook();
                          _usersController.refreshLevelPercentage();
                          Future.delayed(Duration(milliseconds: 1800), (() {
                            showSnackMsg('${statusMessage.message}');
                            // Get.snackbar(
                            //     'Message'.tr, '${statusMessage.message}',
                            //     backgroundColor: Theme.of(context).primaryColor,
                            //     colorText: Theme.of(context).primaryColorLight,
                            //     snackPosition: SnackPosition.BOTTOM);
                          }));
                        }
                      });
                    }));
                    // _booksController.readProgress(widget.bookId,
                    //     widget.assignmentId, 100, widget.readingType);
                    // Future.delayed(Duration(milliseconds: 7000), (() {
                    //   if (_booksController.statusMessageResult.value.status ==
                    //       1000) {
                    //     //isFinished = true;
                    //     var message =
                    //         _booksController.statusMessageResult.value.message;
                    //     Get.snackbar('Message'.tr, '$message',
                    //         backgroundColor: Theme.of(context).primaryColor,
                    //         colorText: Theme.of(context).primaryColorLight,
                    //         snackPosition: SnackPosition.BOTTOM);
                    //   }
                    // }));
                  }
                },
              ),
              progress < 1.0
                  ? LinearProgressIndicator(value: progress)
                  : Container(),
            ],
          ),
        ),
      ])),
      floatingActionButton: Obx(() {
        if (_booksController.showBookBarRecord.value) {
          return DraggableFab(
              child: Container(
            // width: MediaQuery.of(context).size.width,
            padding: EdgeInsets.all(10.0),
            height: 160,
            width: 320,
            decoration: BoxDecoration(
              color: Color.fromARGB(209, 236, 241, 241),
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(10.0),
                topLeft: Radius.circular(10.0),
                bottomLeft: Radius.circular(10.0),
                bottomRight: Radius.circular(10.0),
              ),
            ),
            child: MyRecorder(
                bookId: widget.bookId, assignmentId: widget.assignmentId),
          ));
        } else if (_booksController.showBookBarSetting.value) {
          // set inital setting
          if (box.get(CacheManagerKey['_text'].toString()) == 'Simplified') {
            text = TextOptions.Simplified;
          } else if (box.get(CacheManagerKey['_text'].toString()) ==
              'Traditional') {
            text = TextOptions.Traditional;
          } else {
            text = TextOptions.notext;
          }
          if (box.get(CacheManagerKey['_audio'].toString()) == 'Mandarin') {
            audio = AudioOptions.Mandarin;
          } else if (box.get(CacheManagerKey['_audio'].toString()) ==
              'Cantonese') {
            audio = AudioOptions.Cantonese;
          } else {
            audio = AudioOptions.No_audio;
          }
          if (box.get(CacheManagerKey['_auto'].toString()) == 'True') {
            auto = AutoplayOptions.True;
          } else {
            auto = AutoplayOptions.False;
          }
          if (box.get(CacheManagerKey['_pinyin'].toString()).toString() ==
              'True') {
            pinyinS = PinyinOptions.True;
          } else {
            pinyinS = PinyinOptions.False;
          }
          return Container(
            height: MediaQuery.of(context).size.height * 0.87,
            width: 300,
            decoration: BoxDecoration(
              color: Color.fromARGB(209, 236, 241, 241),
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(10.0),
                topLeft: Radius.circular(10.0),
                bottomLeft: Radius.circular(10.0),
                bottomRight: Radius.circular(10.0),
              ),
            ),
            child: MyBookSettings(
              bookId: widget.bookId,
              assignmentId: widget.assignmentId,
            ),
          );
        } else {
          return Text('');
        }
      }),
    );
  }
}

class MyBookSettings extends StatefulWidget {
  const MyBookSettings({
    Key? key,
    this.bookId,
    this.assignmentId,
  }) : super(key: key);
  final String? bookId;
  final String? assignmentId;
  @override
  State<MyBookSettings> createState() => _MySetting();
}

class _MySetting extends State<MyBookSettings> {
  TextOptions? _text = text;
  AudioOptions? _audio = audio;
  AutoplayOptions? _auto = auto;
  PinyinOptions? _pinyin = pinyinS;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
          height: 720,
          width: 200,
          child: Column(children: [
            Text('Text Setting',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Color.fromARGB(156, 0, 0, 0).withOpacity(0.8),
                    fontSize: 19)),
            RadioListTile<TextOptions>(
              title: const Text('Simplified'),
              value: TextOptions.Simplified,
              groupValue: _text,
              onChanged: (TextOptions? value) {
                setState(() {
                  _text = value;
                  box.put(CacheManagerKey['_text'].toString(), 'Simplified');
                  globalController.evaluateJavascript(source: "showText('s')");
                });
              },
            ),
            RadioListTile<TextOptions>(
              title: const Text('Traditional'),
              value: TextOptions.Traditional,
              groupValue: _text,
              onChanged: (TextOptions? value) {
                setState(() {
                  _text = value;
                  box.put(CacheManagerKey['_text'].toString(), 'Traditional');
                  globalController.evaluateJavascript(source: "showText('t')");
                });
              },
            ),
            RadioListTile<TextOptions>(
              title: const Text('No Text'),
              value: TextOptions.notext,
              groupValue: _text,
              onChanged: (TextOptions? value) {
                setState(() {
                  _text = value;
                  box.put(CacheManagerKey['_text'].toString(), 'notext');
                  globalController.evaluateJavascript(source: "hideText()");
                });
              },
            ),
            SizedBox(height: 20),
            Text('Language Setting',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Color.fromARGB(156, 0, 0, 0).withOpacity(0.8),
                    fontSize: 19)),
            RadioListTile<AudioOptions>(
              title: const Text('Mandarin'),
              value: AudioOptions.Mandarin,
              groupValue: _audio,
              onChanged: (AudioOptions? value) {
                setState(() {
                  _audio = value;
                  box.put(CacheManagerKey['_audio'].toString(), 'Mandarin');
                  globalController.evaluateJavascript(source: "readOn()");
                  globalController.evaluateJavascript(source: "bgmOn()");
                  globalController.evaluateJavascript(
                      source: "fLangToggle('m')");
                });
              },
            ),
            RadioListTile<AudioOptions>(
              title: const Text('Cantonese'),
              value: AudioOptions.Cantonese,
              groupValue: _audio,
              onChanged: (AudioOptions? value) {
                setState(() {
                  _audio = value;
                  box.put(CacheManagerKey['_audio'].toString(), 'Cantonese');
                  globalController.evaluateJavascript(source: "readOn()");
                  globalController.evaluateJavascript(source: "bgmOn()");
                  globalController.evaluateJavascript(
                      source: "fLangToggle('c')");
                });
              },
            ),
            RadioListTile<AudioOptions>(
              title: const Text('No Audio'),
              value: AudioOptions.No_audio,
              groupValue: _audio,
              onChanged: (AudioOptions? value) {
                setState(() {
                  _audio = value;
                  box.put(CacheManagerKey['_audio'].toString(), 'No_audio');
                  globalController.evaluateJavascript(source: "readOff()");
                  globalController.evaluateJavascript(source: "bgmOff()");
                });
              },
            ),
            SizedBox(height: 20),
            Text('Autoplay Setting',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Color.fromARGB(156, 0, 0, 0).withOpacity(0.8),
                    fontSize: 19)),
            RadioListTile<AutoplayOptions>(
              title: const Text('On'),
              value: AutoplayOptions.True,
              groupValue: _auto,
              onChanged: (AutoplayOptions? value) {
                setState(() {
                  _auto = value;
                  box.put(CacheManagerKey['_auto'].toString(), 'True');
                  globalController.evaluateJavascript(source: "autoplayOn()");
                });
              },
            ),
            RadioListTile<AutoplayOptions>(
              title: const Text('Off'),
              value: AutoplayOptions.False,
              groupValue: _auto,
              onChanged: (AutoplayOptions? value) {
                setState(() {
                  _auto = value;
                  box.put(CacheManagerKey['_auto'].toString(), 'False');
                  globalController.evaluateJavascript(source: "autoplayOff()");
                });
              },
            ),
            SizedBox(height: 20),
            Text('Pinyin Setting',
                style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Color.fromARGB(156, 0, 0, 0).withOpacity(0.8),
                    fontSize: 19)),
            RadioListTile<PinyinOptions>(
              title: const Text('On'),
              value: PinyinOptions.True,
              groupValue: _pinyin,
              onChanged: (PinyinOptions? value) {
                setState(() {
                  _pinyin = value;
                  box.put(CacheManagerKey['_pinyin'].toString(), 'True');
                  globalController.evaluateJavascript(source: "showPinyin()");
                });
              },
            ),
            RadioListTile<PinyinOptions>(
              title: const Text('Off'),
              value: PinyinOptions.False,
              groupValue: _pinyin,
              onChanged: (PinyinOptions? value) {
                setState(() {
                  _pinyin = value;
                  box.put(CacheManagerKey['_pinyin'].toString(), 'False');
                  globalController.evaluateJavascript(source: "hidePinyin()");
                });
              },
            ),
          ]),
        )
      ],
    );
  }
}
